package com.easemob.helpdesk.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.easemob.helpdesk.bean.User;
import com.housekeeperapp.MainApplication;
import com.housekeeperapp.R;
import com.easemob.helpdesk.activity.ChatActivity;
import com.easemob.helpdesk.activity.MainActivity;
import com.easemob.helpdesk.adapter.CurrentSessionAdapter;
import com.easemob.helpdesk.listener.OnItemClickListener;
import com.easemob.helpdesk.utils.EMToast;
import com.easemob.helpdesk.utils.OnFreshCallbackListener;
import com.easemob.helpdesk.utils.OnRefreshViewListener;
import com.easemob.helpdesk.widget.recyclerview.DividerLine;
import com.easemob.helpdesk.EMValueCallBack;
import com.hyphenate.kefusdk.HDDataCallBack;
//import com.hyphenate.kefusdk.bean.HDSession;
import com.hyphenate.kefusdk.chat.HDClient;
import com.hyphenate.kefusdk.entity.HDSession;
import com.hyphenate.kefusdk.gsonmodel.customer.CustomerInfoResponse;
import com.hyphenate.kefusdk.manager.session.CloseSessionManager;
import com.hyphenate.kefusdk.manager.session.CurrentSessionManager;
import com.hyphenate.kefusdk.manager.session.OverTimeSessionManager;
import com.hyphenate.kefusdk.utils.HDLog;
import com.hyphenate.util.NetUtils;
import com.net.ApiService;
import com.net.HKResponseResultCallBack;
import com.net.HKHttpUtils;

import java.util.List;


//import okhttp3.Call;
import retrofit2.Call;

/**
 * Created by liyuzhao on 05/04/2017.
 */

public class CurrentSessionFragment extends Fragment implements OnRefreshViewListener, SwipeRefreshLayout.OnRefreshListener, CloseSessionManager.CloseSessionListener, OverTimeSessionManager.OverTimeSessionListener, OnFreshCallbackListener {
	private static final String TAG = CurrentSessionFragment.class.getSimpleName();

	private InputMethodManager inputMethodManager;
	private  void initFindView(View view){
		mRecyclerView=view.findViewById(R.id.list);

		query=view.findViewById(R.id.query);
		mSwipeLayout=view.findViewById(R.id.swipe_layout);
		emptyView=view.findViewById(R.id.emptyView);
		clearSearch=view.findViewById(R.id.search_clear);


	}
	public RecyclerView mRecyclerView;
	private CurrentSessionAdapter adapter;
	public EditText query;
	public ImageButton clearSearch;
	public static OnFreshCallbackListener callback= null;
	public static OnRefreshViewListener refreshCallback = null;
	public static CurrentSessionFragment instance = null;

	public SwipeRefreshLayout mSwipeLayout;
	public View emptyView;


//	@BindView(R.id.rl_message_back)
//	public RelativeLayout relativeLayout;
	private MsgFragment msgFragment;

//	public CurrentSessionFragment(){
//
//	}

	public void setMsgFragment(MsgFragment msg){
		msgFragment = msg;
	}

	@Nullable
	@Override
	public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.fragment_currentsession, null);
		initFindView(view);
		return view;
	}

	private void getUserInfo(long id, final HDSession sEntty, final String val) {

		ApiService apiService = HKHttpUtils.getApiService();
		Call userById = apiService.getUserById(MainActivity.ticket,String.valueOf(id));
		userById.enqueue(new HKResponseResultCallBack<User>() {

			@Override
			public void onSuccess(User user) {
				if(user != null){
					Intent intent = new Intent();
					intent.setClass(getActivity(), ChatActivity.class);
					intent.putExtra("truename", user.getName());
					intent.putExtra("user_phone",  user.getPhone());
					intent.putExtra("username", val);
					intent.putExtra("addr",user.getHomeAddress());

					intent.putExtra("hasUnReadMessage", sEntty.hasUnReadMessage());
					intent.putExtra("user",  sEntty.getUser());
					intent.putExtra("originType",sEntty.getOriginType());
					intent.putExtra("techChannelName",sEntty.getTechChannelName());
					intent.putExtra("visitorid", sEntty.getServiceSessionId());
					intent.putExtra("chatGroupId", sEntty.getChatGroupId());
					intent.putExtra("isVip",user.getIsVip());
					startActivity(intent);
				}
			}

			@Override
//<<<<<<< HEAD
//			public void onResponse(Call call, Response response) throws IOException {
//
//				final String res = response.body().string();
//				final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//				getActivity().runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						if(result.getData() != null){
//							Intent intent = new Intent();
//							intent.setClass(getActivity(), ChatActivity.class);
//							intent.putExtra("truename", result.getData().getName());
//							intent.putExtra("user_phone",  result.getData().getPhone());
//							intent.putExtra("username", val);
//							intent.putExtra("addr", result.getData().getHomeAddress());
//
//							intent.putExtra("hasUnReadMessage", sEntty.hasUnReadMessage());
//							intent.putExtra("user",  sEntty.getUser());
//							intent.putExtra("originType",sEntty.getOriginType());
//							intent.putExtra("techChannelName",sEntty.getTechChannelName());
//							intent.putExtra("visitorid", sEntty.getServiceSessionId());
//							intent.putExtra("chatGroupId", sEntty.getChatGroupId());
//							startActivity(intent);
//						}
//					}
//				});
//=======
			public void onGetDataFailed(int cd, String msg) {
				Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
			}
//>>>>>>> master-temp

			@Override
			public void onFailed(retrofit2.Call call, Throwable t) {
				Toast.makeText(getContext(), "请求失败", Toast.LENGTH_SHORT).show();
			}
		});


//		OkHttpClient okHttpClient = new OkHttpClient();
//
//		RequestBody body = new FormBody.Builder()
//				.add("uid", String.valueOf(id))
//				.build();
//
//		Request request = new Request.Builder()
//				.url(BuildConfig.API_URL + "account/findUserById")
//				.post(body)
//				.build();
//
//		Call call = okHttpClient.newCall(request);
//
//		call.enqueue(new Callback() {
//			@Override
//			public void onFailure(Call call, IOException e) {
//				e.printStackTrace();
//				getActivity().runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						Toast.makeText(getContext(), "请求失败", Toast.LENGTH_SHORT).show();
//					}
//				});
//
//			}
//
//			@Override
//			public void onResponse(Call call, Response response) throws IOException {
//
//				final String res = response.body().string();
//				final UserInfo result = CommonUtils.parseJsonWithGson(res, UserInfo.class);
//				getActivity().runOnUiThread(new Runnable() {
//					@Override
//					public void run() {
//						if(result.getData() != null){
//							Intent intent = new Intent();
//							intent.setClass(getActivity(), ChatActivity.class);
//							intent.putExtra("truename", result.getData().getName());
//							intent.putExtra("user_phone",  result.getData().getPhone());
//							intent.putExtra("username", val);
//
//							intent.putExtra("hasUnReadMessage", sEntty.hasUnReadMessage());
//							intent.putExtra("user",  sEntty.getUser());
//							intent.putExtra("originType",sEntty.getOriginType());
//							intent.putExtra("techChannelName",sEntty.getTechChannelName());
//							intent.putExtra("visitorid", sEntty.getServiceSessionId());
//							intent.putExtra("chatGroupId", sEntty.getChatGroupId());
//							startActivity(intent);
//						}
//					}
//				});
//
//			}
//		});

	}

	@Override
	public void onActivityCreated(@Nullable Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);
		callback = this;
		refreshCallback = this;
		instance = this;

		inputMethodManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);

		//创建一个线性布局管理器
		final LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
		//设置布局管理器
		mRecyclerView.setLayoutManager(layoutManager);
		//设置分割线
		DividerLine dividerLine = new DividerLine(DividerLine.VERTICAL);
		dividerLine.setSize(1);
		dividerLine.setColor(0xFFDDDDDD);
		mRecyclerView.addItemDecoration(dividerLine);
		mRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
			@Override
			public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
				super.onScrolled(recyclerView, dx, dy);
				boolean enable;
				if(mRecyclerView!= null && layoutManager.getChildCount()>0){
					boolean firstItemVisible = layoutManager.findFirstVisibleItemPosition() == 0;
					boolean topOfFirstItemVisible = layoutManager.findFirstCompletelyVisibleItemPosition() == 0;
					enable = firstItemVisible && topOfFirstItemVisible;
					mSwipeLayout.setEnabled(enable);
				}else{
					mSwipeLayout.setEnabled(true);
				}
			}
		});
		mSwipeLayout.setOnRefreshListener(this);
		mSwipeLayout.setColorSchemeResources(R.color.holo_blue_bright, R.color.holo_green_dark, R.color.holo_orange_light, R.color.holo_red_light);
		adapter = new CurrentSessionAdapter(getActivity(), mSwipeLayout);
		mRecyclerView.setAdapter(adapter);
		adapter.registerAdapterDataObserver(mObserver);
		mObserverAttached = true;
		updateEmptyStatus(isEmpty());
		adapter.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onClick(View itemView, int position) {
				final HDSession sEntty = adapter.getItem(position);
				if(sEntty == null){
					return;
				}

				HDClient.getInstance().visitorManager().getCustomerDetailInfo(sEntty.getUser().getTenantId(), sEntty.getUser().getUserId(), new HDDataCallBack<CustomerInfoResponse.EntityBean>() {
					@Override
					public void onSuccess(final CustomerInfoResponse.EntityBean entityBean) {

						getActivity().runOnUiThread(new Runnable() {

							@Override
							public void run() {
								List<CustomerInfoResponse.EntityBean.ColumnValuesBean> columnValues = entityBean.getColumnValues();

								for (int i = 0; i < columnValues.size(); i++) {
									String col_name = columnValues.get(i).getColumnName();
									String val = "";
									if(columnValues.get(i).getValues().size() > 0){
										//环信升级后有修改 修改前======val = columnValues.get(i).getValues().get(0);
										val = columnValues.get(i).getValues().get(0).toString();
									}

									if(col_name.equals("username")){

										if(!TextUtils.isEmpty(val) && val.contains("#")){
											String uid = val.split("#")[0];
											getUserInfo(Long.parseLong(uid), sEntty, val);
										}
									}
								}


							}
						});


					}

					@Override
					public void onError(final int error, final String errorMsg) {
						if (getActivity() == null) {
							return;
						}
						getActivity().runOnUiThread(new Runnable() {

							@Override
							public void run() {
								if (mSwipeLayout != null) {
									mSwipeLayout.setRefreshing(false);
								}
								Toast.makeText(getActivity(), "获取用户信息失败，请稍后重试"+String.valueOf(error)+errorMsg, Toast.LENGTH_SHORT).show();
							}
						});
					}
				});

//				HDMessage lastMessage = sEntty.getLastChatMessage();
//				if(lastMessage != null){
//					JSONObject extJson = lastMessage.getExtJson();
//					if(extJson != null && extJson.has("weichat")) {
//						try {
//							JSONObject jsonWeichat = extJson.getJSONObject("weichat");
//							if(jsonWeichat != null) {
//								JSONObject visitorJson = jsonWeichat.getJSONObject("visitor");
//								if(visitorJson != null){
//									String phone = visitorJson.getString("phone");
//									intent.putExtra("user_phone",  phone);
//								}
//							}
//
//						} catch (JSONException var3) {
//							var3.printStackTrace();
//						}
//					}
//				}



//				getActivity().overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
			}
		});
		// 搜索框
		String strSearch ="请输入姓名或地址";
		query.setHint(strSearch);
		query.addTextChangedListener(new TextWatcher() {
			@Override
			public void onTextChanged(CharSequence s, int start, int before,
			                          int count) {
				adapter.getFilter().filter(s);
				if(msgFragment != null){
					msgFragment.clearFilter();
				}

				if (s.length() > 0) {
					clearSearch.setVisibility(View.VISIBLE);
				} else {
					clearSearch.setVisibility(View.INVISIBLE);
				}
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
			                              int after) {
			}

			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		clearSearch.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				query.getText().clear();
				hideSoftKeyboard();
			}

		});

//		relativeLayout.setOnClickListener(new View.OnClickListener() {
//			@Override
//			public void onClick(View v) {
//				getActivity().finish();
//				getActivity().overridePendingTransition(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
//			}
//		});

		CurrentSessionManager.getInstance().getSessionsFromServer(new HDDataCallBack<List<HDSession>>() {
			@Override
			public void onSuccess(List<HDSession> value) {
				if (getActivity() == null) {
					return;
				}
				getActivity().runOnUiThread(new Runnable() {

					@Override
					public void run() {
						adapter.refresh();
						refreshSessionLabel();
					}
				});
			}

			@Override
			public void onError(final int error, final String errorMsg) {
				if (getActivity() == null) {
					return;
				}
				getActivity().runOnUiThread(new Runnable() {

					@Override
					public void run() {
						if (mSwipeLayout != null) {
							mSwipeLayout.setRefreshing(false);
						}
						Toast.makeText(getActivity(), "刷新信息列表失败，请稍后重试"+String.valueOf(error)+errorMsg, Toast.LENGTH_SHORT).show();
					}
				});
			}
		});


	}

	void hideSoftKeyboard() {
		if (getActivity().getWindow().getAttributes().softInputMode != WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN) {
			if (getActivity().getCurrentFocus() != null){
				inputMethodManager.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(),
						InputMethodManager.HIDE_NOT_ALWAYS);
			}
		}
	}

	public CurrentSessionAdapter getAdapter(){
		return adapter;
	}


	@Override
	public void onFresh(final EMValueCallBack callback) {
		CurrentSessionManager.getInstance().getSessionsFromServer(new HDDataCallBack<List<HDSession>>() {
			@Override
			public void onSuccess(List<HDSession> value) {
				if (getActivity() == null) {
					return;
				}
				getActivity().runOnUiThread(new Runnable() {

					@Override
					public void run() {
						adapter.refresh();
						refreshSessionLabel();
						if (mSwipeLayout != null) {
							mSwipeLayout.setRefreshing(false);
						}
						if (callback != null) {
							callback.onSuccess(null);
						}
					}
				});
			}

			@Override
			public void onError(final int error, final String errorMsg) {
				if (getActivity() == null) {
					return;
				}
				HDLog.e(TAG, "error:" + errorMsg);
				getActivity().runOnUiThread(new Runnable() {

					@Override
					public void run() {
						if (mSwipeLayout != null) {
							mSwipeLayout.setRefreshing(false);
						}
						if (callback != null) {
							callback.onError(error, errorMsg);
						}
					}
				});
			}
		});
	}

	private void updateEmptyStatus(boolean empty){
		if(empty){
			mRecyclerView.setVisibility(View.GONE);
			if(emptyView != null){
				emptyView.setVisibility(View.VISIBLE);
			}
		}else{
			if(mRecyclerView != null){
				mRecyclerView.setVisibility(View.VISIBLE);
			}

			if(emptyView != null){
				emptyView.setVisibility(View.GONE);
			}
		}
	}
	private boolean mObserverAttached = false;
	@Override
	public void onDetach() {
		super.onDetach();
		if(adapter != null && mObserverAttached){
			adapter.unregisterAdapterDataObserver(mObserver);
			mObserverAttached = false;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		CloseSessionManager.getInstance().addCloseSessionListener(this);
		OverTimeSessionManager.getInstance().addOverTimeSessionListener(this);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();

		CloseSessionManager.getInstance().removeCloseSessionListener(this);
		OverTimeSessionManager.getInstance().removeOverTimeSessionListener(this);
	}

	private boolean isEmpty(){
		return adapter == null ? true : adapter.getItemCount() == 0;
	}
	private RecyclerView.AdapterDataObserver mObserver = new RecyclerView.AdapterDataObserver() {
		@Override
		public void onChanged() {
			super.onChanged();
			updateEmptyStatus(isEmpty());
		}

		@Override
		public void onItemRangeChanged(int positionStart, int itemCount) {
			super.onItemRangeChanged(positionStart, itemCount);
			updateEmptyStatus(isEmpty());
		}

		@Override
		public void onItemRangeInserted(int positionStart, int itemCount) {
			super.onItemRangeInserted(positionStart, itemCount);
			updateEmptyStatus(isEmpty());
		}

		@Override
		public void onItemRangeRemoved(int positionStart, int itemCount) {
			super.onItemRangeRemoved(positionStart, itemCount);
			updateEmptyStatus(isEmpty());
		}
	};

	public int getUnreadCount() {
		return CurrentSessionManager.getInstance().getTotalUnReadCount();
	}

	private void refreshSessionLabel() {
		if(msgFragment != null){
			try {
				String s = msgFragment.getmTabLayout().getMsgView(0).getText().toString();
				if (!TextUtils.isEmpty(s)) {
					int waitCount = Integer.parseInt(s);
					((MainActivity) getActivity()).refreshSessionUnreadCount(waitCount);
				}

			} catch (NumberFormatException e) {
				e.printStackTrace();
			}

		}else{
			((MainActivity) getActivity()).refreshSessionUnreadCount(0);
		}

	}

	@Override
	public void onRefreshView() {
		adapter.refresh();
		refreshSessionLabel();
	}

	@Override
	public void onRefresh() {
		onFresh(null);
	}


	@Override
	public void close(final String sSessionId) {
		if(getActivity() == null){
			return;
		}
		getActivity().runOnUiThread(new Runnable() {

			@Override
			public void run() {
				HDSession session = CurrentSessionManager.getInstance().getSessionEntity(sSessionId);
				if (session != null) {
					CurrentSessionManager.getInstance().remove(sSessionId);
					query.getText().clear();
					onRefreshView();
				}
			}
		});
	}

	@Override
	public void closeSession(String sSessionId) {
		HDSession session = CurrentSessionManager.getInstance().getSessionEntity(sSessionId);
		if (session != null) {
			CurrentSessionManager.getInstance().remove(sSessionId);
			EMToast.makeStyleableToast(getActivity(), "会话超时已关闭！").show();
			onRefreshView();
		}
	}


	@Override
	public void onDestroyView() {
		super.onDestroyView();

	}


}
